import { useInterval } from 'ahooks';
import styles from './index.module.less';
import { orderBookApi } from '@/api';
import { useEffect, useState } from 'react';
import { arrSum, countUsdtNum, formatNum, formatNumUnit, handleNan } from '@/utils';
import { useAtomValue, useSetAtom } from 'jotai';
import { coinAtom, panKouPriceAtom } from '@/stores';
import arrowUp from '@/assets/img/arrow_up.png';
import arrowDown from '@/assets/img/arrow_down.png';
import useRoute from '@/hooks/useRoute';
import { lunXunTime } from '@/utils/helper';

export default function Dish() {
  const setPanKouPrice = useSetAtom(panKouPriceAtom);
  const [data, setData] = useState<any>(null);
  const coinData = useAtomValue(coinAtom);
  const { getPageParams } = useRoute();
  const curContract = getPageParams('contract');

  useEffect(() => {
    getOrderBook();
  }, []);

  useInterval(() => {
    getOrderBook(); // 市场深度信息
  }, lunXunTime);

  // 市场深度信息
  async function getOrderBook() {
    const params = {
      limit: 10,
      contract: curContract,
      interval: 0.5,
    };
    const res: any = (await orderBookApi(params))?.data;
    // console.log('res: 市场深度信息', res);
    res.asks = res?.asks?.reverse();
    const newres = handleLeiji(res);
    setData(newres);
  }

  // 处理累计
  function handleLeiji(res: any) {
    const asksLj = arrSum(res?.asks?.map((item: any) => item?.s));
    const bidsLj = arrSum(res?.bids?.map((item: any) => item?.s));
    res.asks = res?.asks?.map((item: any, i: number) => ({ ...item, lj: asksLj[i] }));
    res.bids = res?.bids?.map((item: any, i: number) => ({ ...item, lj: bidsLj[i] }));
    const askbl = Number(((asksLj[0] / (asksLj[0] + bidsLj[0])) * 10000).toFixed(0));
    res.bili = { askbl, bidbl: 10000 - askbl };
    // console.log('res:盘口 ', res);
    return res;
  }

  // dom
  const PanKouRow = ({ item, color }: any) => (
    <div className={`${styles.trow} ${styles.trowsell}`} onClick={() => rowClick(item?.p)}>
      <div className={`${styles.tc} ${color}`}>{formatNum(item?.p, 1)}</div>
      <div className={`${styles.tc} ${styles.tcm}`}>
        {!coinData
          ? '-'
          : formatNumUnit(Math.abs(countUsdtNum(item?.p, item?.s, coinData?.quanto_multiplier)), 1)}
      </div>
      <div className={`${styles.tc} ${styles.tcr}`}>
        {!coinData
          ? '-'
          : formatNumUnit(
              Math.abs(countUsdtNum(item?.p, item?.lj, coinData?.quanto_multiplier)),
              1,
            )}
      </div>
    </div>
  );

  function rowClick(data: any) {
    setPanKouPrice(data);
  }

  return (
    <div className={`${styles.dishwrap} `}>
      <div className={`${styles.ratiow}`}>
        <div className={`${styles.dtopwrap} `}>
          <div className={`${styles.buybg} `}></div>
        </div>
        <div className={`${styles.dbot}`}>
          <div className={`${styles.buytxt} color-red`}>买入{data?.bili?.bidbl / 100}%</div>
          <div className={`${styles.buytxt} color-green`}>卖出{data?.bili?.askbl / 100}%</div>
        </div>
      </div>
      <div className={`${styles.dlistwrap} xxx`}>
        <div className={`${styles.trow} ${styles.th}`}>
          <div className={`${styles.tc}`}>委托价</div>
          <div className={`${styles.tc} ${styles.tcm}`}>数量(USDT)</div>
          <div className={`${styles.tc} ${styles.tcr}`}>累计(USDT)</div>
        </div>
        {data?.asks && (
          <>
            {data?.asks
              ?.filter((_: any, i: number) => i < 10)
              .map((item: any, i: number) => <PanKouRow item={item} key={i} color="color-green" />)}
            <div className={`${styles.sellRowInfo}`}>
              <div
                className={`${styles.num1} ${data?.change_percentage > 0 ? 'color-red' : 'color-green'}`}
              >
                {coinData?.last}
                <img src={data?.change_percentage > 0 ? arrowUp : arrowDown} alt="" />
              </div>
              <div className={`${styles.num2} xxx`}>{coinData?.mark_price}</div>
            </div>
            {data?.bids
              ?.filter((item: any, i: number) => i < 10)
              .map((item: any, i: number) => <PanKouRow item={item} key={i} color="color-red" />)}
          </>
        )}
      </div>
      <div className={`${styles.xxx} xxx`}></div>
    </div>
  );
}
